package a66weding.com.jiehuntong.http;


import android.content.Context;
import android.text.TextUtils;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.xutils.HttpManager;
import org.xutils.common.Callback;
import org.xutils.ex.HttpException;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import a66weding.com.jiehuntong.beans.ErrorBean;
import a66weding.com.jiehuntong.beans.HttpRequestBean;
import a66weding.com.jiehuntong.beans.SuccessBean;
import a66weding.com.jiehuntong.common.utils.CUtils;
import a66weding.com.jiehuntong.common.utils.LogUtil;
import a66weding.com.jiehuntong.common.utils.StrUtil;

/**
 * @version :
 * @creator : AxDu
 * @create-time : 2016/5/26
 * @description :使用xutils发送http请求
 */
public class XutilHttp {

    //请求成功
    public static final String RESULT_SUCCESS = "0";
    // 请求失败
    public static final String RESULT_FAIL = "1";

    protected Context context;
    protected OnNetResultListener mOnNetListener;
    protected Type mType;
    private Class mClass;
    protected String mRequestCode;
    protected HttpRequestBean mHttpBean;
    private HttpManager xhttp;
    private Callback.Cancelable xhttpCallback;


    public XutilHttp(Context context, HttpRequestBean httpbean) {
        this.context = context;
        this.mOnNetListener = httpbean.getListener();
        this.mType = httpbean.getT();
        mClass = httpbean.getClazz();
        this.mRequestCode = httpbean.getRequestCode();
        this.mHttpBean = httpbean;
        xhttp = x.http();
    }


    /**
     * 发起get网络请求
     *
     * @param
     */
    public void execute() {
        //判断网络状态
        boolean networkAvailable = NetStatusUtil.isNetworkAvailable(context);
        NetStatusUtil.NetState connected = NetStatusUtil.isConnected(context);

        if (networkAvailable) {

            //根据请求码，请求对应的接口服务
            switch (mHttpBean.getRequestMethod()) {
                case RequestCode.GETREQUEST://get请求
                    getDataFromNetForXutil_Get(mHttpBean);
                    break;
                case RequestCode.POSTEQUEST://post请求
                    getDataFromNetForXutil_Post(mHttpBean);
                    break;
            }
        } else {
            ErrorBean err = new ErrorBean(ErrorBean.NONET, "无网络", mRequestCode);
            if (mOnNetListener != null) {
                mOnNetListener.onError(err);
            }
            CUtils.showToast("网络请求失败，请检查网络情况");
        }
    }

    private void getDataFromNetForXutil_Post(HttpRequestBean requestBean) {
        //接收响应的结果信息
        final HashMap<String, String> resultMap = new HashMap<String, String>();
        RequestParams requestParams = new RequestParams(requestBean.getUrl());
        HashMap paramsMap = requestBean.getParamsMap();
        StringBuffer stringBuffer = new StringBuffer();
        if (paramsMap != null) {
            setParams(requestParams, paramsMap);
            Iterator iter = paramsMap.entrySet().iterator();
            while (iter.hasNext()) {
                Map.Entry entry = (Map.Entry) iter.next();
                Object key = entry.getKey();
                Object val = entry.getValue();
                stringBuffer.append(entry.getKey()+":"+entry.getValue()+" ");
            }
        }
        String params = stringBuffer.toString();
        LogUtil.i("httpUtils", "postUrl:" + requestBean.getUrl() +
                (!TextUtils.isEmpty(params) ? " postParams:" + params : ""));
        xhttpCallback = xhttp.post(requestParams, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                LogUtil.i("httpUtils", "postResult:" + result);
                if (!TextUtils.isEmpty(result)) {
                    resultMap.put("code", RESULT_SUCCESS);
                    resultMap.put("data", result);
                    try {
                        //解析数据
                        processeData(resultMap);
                    } catch (Exception e) {
                        e.printStackTrace();
                        LogUtil.i("httpUtils", "postException:" + e.toString());
                        CUtils.showToast("数据解析错误");
                    }
                }

            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                LogUtil.i("httpUtils", "postError:" + ex.toString());
//                CUtils.showToast("网络不好,请稍后再试!");
                ErrorBean err = null;
                if (ex instanceof HttpException) { // 网络错误
                    HttpException httpEx = (HttpException) ex;
                    int responseCode = httpEx.getCode();
                    String responseMsg = httpEx.getMessage();
                    String errorResult = httpEx.getResult();
                    err = new ErrorBean(ErrorBean.DATAERROR, responseMsg, mRequestCode);

                } else if ("java.lang.NullPointerException".equals(ex.toString())) {
                    return;
                } else { // 其他错误
                    Type err_type = new TypeToken<ErrorBean>() {
                    }.getType();
                    err = new ErrorBean(ErrorBean.DATAERROR, "其他错误信息", mRequestCode);
                }
                if (mOnNetListener != null) {
                    mOnNetListener.onError(err);
                }
            }

            @Override
            public void onCancelled(CancelledException cex) {
            }

            @Override
            public void onFinished() {
            }
        });

    }


    private void getDataFromNetForXutil_Get(HttpRequestBean requestBean) {
        //接收响应的结果信息
        final HashMap<String, String> resultMap = new HashMap<String, String>();
        RequestParams requestParams = new RequestParams(requestBean.getUrl());
        LogUtil.i("httpUtils", "getUrl:" + requestBean.getUrl());
        xhttp.get(requestParams, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                LogUtil.i("httpUtils", "getResult:" + result);
                if (result != null) {
                    resultMap.put("code", RESULT_SUCCESS);
                    resultMap.put("data", result);
                    try {
                        //解析数据
                        processeData(resultMap);
                    } catch (Exception e) {
                        e.printStackTrace();
                        LogUtil.i("httpUtils", "getException:" + e.toString());
                        CUtils.showToast("数据解析错误");
                    }
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                LogUtil.i("httpUtils", "getError:" + ex.toString());
//                CUtils.showToast("网络不好,请稍后再试!");
                ErrorBean err = new ErrorBean(RESULT_FAIL, ex.getMessage(), mRequestCode);
                if (ex instanceof HttpException) { // 网络错误
                    HttpException httpEx = (HttpException) ex;
                    int responseCode = httpEx.getCode();
                    String responseMsg = httpEx.getMessage();
                    String errorResult = httpEx.getResult();
                    err = new ErrorBean(ErrorBean.DATAERROR, responseMsg, mRequestCode);

                } else if ("java.lang.NullPointerException".equals(ex.toString())) {
                    return;
                } else { // 其他错误
                    Type err_type = new TypeToken<ErrorBean>() {
                    }.getType();
                    err = new ErrorBean(ErrorBean.DATAERROR, "其他错误信息", mRequestCode);
                }


                if (mOnNetListener != null) {
                    mOnNetListener.onError(err);
                }
            }

            @Override
            public void onCancelled(CancelledException cex) {
                ErrorBean err = new ErrorBean(RESULT_FAIL, cex.getMessage(), mRequestCode);
                if (mOnNetListener != null) {
                    mOnNetListener.onError(err);
                }
            }

            @Override
            public void onFinished() {

            }
        });


    }


    private void setParams(RequestParams requestParams, HashMap<String, String> paramsMap) {
        Set<Map.Entry<String, String>> entries = paramsMap.entrySet();
        for (Map.Entry<String, String> entryset : entries) {
            requestParams.addBodyParameter(entryset.getKey(), entryset.getValue());
        }

    }


    /**
     * 解析数据
     *
     * @param resultMap
     */
    private void processeData(HashMap<String, String> resultMap) throws Exception{
        Gson mGson = new Gson();
        //判断请求网络是否成功后失败
        if (RESULT_SUCCESS.equals(resultMap.get("code"))) {// 成功
            String jsondata = resultMap.get("data");
            if (mClass != null && !TextUtils.isEmpty(jsondata)) {
                String newjsondata = StrUtil.jsonStr(jsondata);
                Object resultObj = mClass.newInstance();
                resultObj = mGson.fromJson(newjsondata, mClass);
                SuccessBean sucessBean = new SuccessBean();
                sucessBean.setData(resultObj);
                sucessBean.setInf(mRequestCode);
                if (mOnNetListener != null) {
                    mOnNetListener.onSucess(sucessBean);
                }
            }
        }
    }


    public void testHttp(HttpRequestBean requestBean) {
        //接收响应的结果信息
        final HashMap<String, String> resultMap = new HashMap<String, String>();
        RequestParams requestParams = new RequestParams(requestBean.getUrl());

        x.http().post(requestParams, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                if (result != null) {
                }

            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                ErrorBean err = new ErrorBean(RESULT_FAIL, ex.getMessage(), mRequestCode);
                if (mOnNetListener != null) {
                    mOnNetListener.onError(err);
                }
            }

            @Override
            public void onCancelled(CancelledException cex) {
                ErrorBean err = new ErrorBean(RESULT_FAIL, cex.getMessage(), mRequestCode);
                if (mOnNetListener != null) {
                    mOnNetListener.onError(err);
                }
            }

            @Override
            public void onFinished() {
            }
        });


    }


}
